//1、导入外部的模块
let http = require('http')
let url = require('url')
let login = require('./js/login.js')
//用于解析username=tom&password=123456格式的字符串为对象
let queryString = require('querystring')

//2、创建服务
let server = http.createServer(function(request, response) {
  //4、设置跨域
  response.setHeader('Access-Control-Allow-Origin', '*')
  //5、解析request对象
  let requestUrl = request.url
  //6、使用url模块对requestUrl解析,加上true参数，query是对象
  let URL = url.parse(requestUrl, true)
  //7、获得请求的路径
  let pathName = URL.pathname
  //8、获得请求参数，使用对象方式
  let str = ''
  //9、监听request的请求并接受参数的过程
  request.on('data', function(data) {
    //每提交一次参数，拼接一个参数 str=username=tom&password=12345
    str += data
  })
  //10、request请求提交参数结束
  request.on('end', function() {
    //把请求参数解析成对象{username:'tom',password:'12345'}
    let obj = queryString.parse(str)
    if (pathName === '/login') {
      response.setHeader('Content-type', 'text/html;charset=UTF-8')
      let object = {}
      if (obj.username === 'admin' && obj.password === '123456') {
        object.meta = { status: 200, msg: '登录成功' }
        object.data = login.person
        response.end(JSON.stringify(object))
      } else {
        object.meta = { status: 201, msg: '错误的用户名或密码' }
        object.data = null
        response.end(JSON.stringify(object))
      }
    }
  })
})

//3、启动服务，监听请求
server.listen(8012, '127.0.0.1', () => {
  console.log(`Server is running on http://127.0.0.1:8012 !`)
})